<template>
  <div>
    <el-card>
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="110px">
        <el-form-item class="m-t" label="菜单个数" prop="menuNum">
          <el-radio-group v-model="formData.menuNum" @change="handleRadio">
            <el-radio v-for="(item, index) in menuNumList" :label="item.value" :key="index">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-for="(item, index) in formData.list" style="display: flex" :key="index">
          <div class="menuTitle">
            <span style="color: #e94c00">*</span>{{ menuTitle(index + 1) }}
          </div>
          <div>
            <el-form-item
              v-if="isRequired(index + 1)"
              label-width="60px"
              class="m-t"
              label="名称"
              :prop="`list.${index}.name`"
              :rules="rules.name"
            >
              <el-input
                class="form-input-large"
                placeholder="请输入底部导航栏名称（1-4个文字）"
                v-model.trim="item.name"
                :onkeyup="(item.name = item.name.replace(/[ ]/g, ''))"
                maxlength="4"
                show-word-limit
              >
              </el-input>
            </el-form-item>
            <el-form-item v-else label-width="60px" class="m-t" label="名称" prop=" ">
              <el-input
                class="form-input-large"
                placeholder="请输入底部导航栏名称（1-4个文字）"
                v-model.trim="item.name"
                :onkeyup="(item.name = item.name.replace(/[ ]/g, ''))"
                maxlength="4"
                show-word-limit
              >
              </el-input>
            </el-form-item>
            <el-form-item
              label-width="60px"
              label="路径"
              :prop="`list.${index}.path`"
              :rules="rules.path"
            >
              <el-select
                v-model="item.path"
                class="form-input-large"
                @change="handleChange($event, item)"
                placeholder="请选择标签类型"
              >
                <el-option
                  v-for="item in pathList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <div class="flex iconClass">
              <el-form-item
                :class="item.defaultImg ? 'exist' : 'unExist'"
                label-width="60px"
                label="图标"
                :prop="`list.${index}.defaultImg`"
                :rules="rules.defaultImg"
              >
                <upload-icon
                  :file-type="['jpg', 'png', 'jpeg']"
                  :file-size="1"
                  name="默认图标"
                  :response-fn="handleAvatarUrlResponse"
                  @on-change="
                    uploadAvatarUrlChange($event, `list.${index}.defaultImg`, index, 'defaultImg')
                  "
                  v-model="item.defaultImg"
                />
                <el-avatar
                  v-if="item.defaultImg"
                  shape="square"
                  size="small"
                  :src="item.defaultImg"
                ></el-avatar>
              </el-form-item>
              <el-form-item
                :class="item.affirmImg ? 'exist' : 'unExist'"
                label-width="0px"
                label=""
                :prop="`list.${index}.affirmImg`"
                :rules="rules.affirmImg"
              >
                <upload-icon
                  :file-type="['jpg', 'png', 'jpeg']"
                  :file-size="1"
                  name="选中图标"
                  :response-fn="handleAvatarUrlResponse"
                  @on-change="
                    uploadAvatarUrlChange($event, `list.${index}.affirmImg`, index, 'affirmImg')
                  "
                  v-model="item.affirmImg"
                />
                <el-avatar
                  v-if="item.affirmImg"
                  shape="square"
                  size="small"
                  :src="item.affirmImg"
                ></el-avatar>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </el-card>
    <div class="footer">
      <el-button plain @click="handleDefault">恢复默认</el-button>
      <el-button type="primary" @click="handleConfirm">保存</el-button>
    </div>
  </div>
</template>

<script>
import UploadIcon from '@/views/operate/finish/components/uploadIcon'
import { deepClone } from '@/utils'
export default {
  name: 'tabBar',
  components: { UploadIcon },
  mixins: [],
  props: {},
  data() {
    return {
      menuNumList: [
        {
          label: '两个',
          value: 2
        },
        {
          label: '三个',
          value: 3
        },
        {
          label: '四个',
          value: 4
        }
      ],
      pathList: [
        {
          label: '首页',
          value: '/pages/home/index'
        },
        {
          label: '分类',
          value: '/pages/sort/index'
        },
        {
          label: '购物车',
          value: '/pages/cart/index'
        },
        {
          label: '我的',
          value: '/pages/my/index'
        }
      ],
      formData: {
        menuNum: 4,
        list: []
      },
      options: {
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      },
      rules: {
        menuNum: [{ required: true, message: '请选择菜单个数', trigger: 'change' }],
        name: [{ required: true, message: '请输入底部导航栏名称（1-4个文字）', trigger: 'blur' }],
        unName: [
          { required: false, message: '请输入底部导航栏名称（1-4个文字）', trigger: 'blur' }
        ],
        path: [{ required: true, message: '请选择指定路径', trigger: 'change' }],
        defaultImg: [{ required: true, message: '请上传默认图标', trigger: 'change' }],
        affirmImg: [{ required: true, message: '请上传选中图标', trigger: 'change' }]
      }
    }
  },
  computed: {
    isRequired() {
      return val => {
        let flag = false
        if (this.formData.list.length === 3) {
          flag = val == 2
        } else if (this.formData.list.length === 5) {
          flag = val == 3
        }
        return !flag
      }
    },
    menuTitle() {
      return val => {
        const labelObj = {
          1: '菜单一',
          2: '菜单二',
          3: '菜单三',
          4: '菜单四',
          5: '菜单五'
        }
        return labelObj[val]
      }
    }
  },
  watch: {},
  created() {
    this.handleMenuInfo()
  },
  mounted() {},
  destroyed() {},
  methods: {
    //获取路径名称
    handleChange(e, item) {
      const obj = this.pathList.find(item => item.value === e)
      if (obj) item.pathName = obj.label
    },
    //获取菜单信息
    handleMenuInfo() {
      this.$http.finish.getMenuInfo().then(res => {
        if (res.status === 200) {
          const { data } = res
          if (!data.length) {
            this.formData.menuNum = 4
            this.handlePushMenu()
          } else {
            this.formData.menuNum = data.length
            this.handlePushMenu()
            this.formData.list = data
          }
        }
      })
    },
    //向数组中添加多个元素
    handlePushMenu() {
      const menuObj = {
        name: '',
        path: '',
        pathName: '',
        defaultImg: '',
        affirmImg: ''
      }
      let list = []
      for (let i = 0; i < this.formData.menuNum; i++) {
        list.push(menuObj)
      }
      this.formData.list = deepClone(list)
    },
    //选择菜单个数
    handleRadio() {
      this.formData.list = []
      this.handlePushMenu()
      this.$nextTick(() => {
        this.$refs.elForm.clearValidate()
      })
    },
    //恢复默认
    handleDefault() {
      this.$http.finish.restoreTabBar().then(res => {
        if (res.status === 200) {
          this.formData.list = []
          this.handleMenuInfo()
          this.$nextTick(() => {
            this.$refs.elForm.clearValidate()
          })
        }
      })
    },

    //保存
    handleConfirm() {
      this.$refs.elForm.validate(valid => {
        this.$refs.elForm.validateField(`list.1.affirmImg`, val => {
          console.log(val)
        })
        if (valid) {
          let loading = this.$loading(this.options)
          const updateList = this.formData.list
          this.$http.finish
            .addTabBar({ updateList })
            .then(res => {
              if (res.status === 200) {
                this.$message.success('保存成功')
                loading.close()
              } else {
                this.$message.error(res.msg)
                loading.close()
              }
            })
            .catch(e => {
              loading.close()
            })
        } else {
          this.$message.warning('有必填项未填，请检查')
        }
      })
    },
    // 上传门店头像
    handleAvatarUrlResponse(response) {
      return response.data.url
    },
    uploadAvatarUrlChange(e, url, index, val) {
      console.log(index, val, url)
      if (this.formData.list[index][val]) {
        this.$refs.elForm.clearValidate(url)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.menuTitle {
  margin-top: 20px;
  height: 36px;
  line-height: 36px;
  margin-left: 40px;
  font-size: 14px;
  color: #606266;
  font-weight: 700;
}

.iconClass {
  /deep/ .el-form-item__content {
    display: flex;
    align-items: center;
  }
  /deep/.el-form-item__error {
    width: 85px;
  }
}

.unExist {
  /deep/ .el-form-item__content {
    display: flex;
    align-items: center;
    margin-right: 75px;
  }
}

.exist {
  /deep/ .el-avatar--small {
    margin: 0 21px;
  }
}
</style>
